package io.github.wanggit.antrpc.commons.bean;

import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

public class IdGenHelper {

    private IdGenHelper() {
        throw new IllegalStateException();
    }

    private static final AtomicInteger atomicInteger = new AtomicInteger(0);

    public static int getId() {
        return atomicInteger.getAndIncrement();
    }

    public static String getUUID() {
        return DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().replace("-", "").getBytes())
                .toLowerCase();
    }

    public static String to16LowHexZipkinId(String content) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
                builder.append(c);
            }
        }
        String result = builder.toString();
        if (result.length() < 16) {
            int val = 16 - result.length();
            for (int i = 0; i < val; i++) {
                result += "0";
            }
        } else if (result.length() > 16) {
            result = result.substring(0, 16);
        }
        return result;
    }

    public static boolean isZipkinIdAllZero(String zipkinId) {
        return "0000000000000000".equals(zipkinId);
    }
}
